'use strict'

const {app: electronApp, Tray, Menu} = require('electron')
const path = require('node:path')
const {getBaseDir} = require('ee-core/ps')
const {logger} = require('ee-core/log')
const {getConfig} = require('ee-core/config')
const {getMainWindow, getCloseAndQuit, setCloseAndQuit} = require('ee-core/electron')
const {appService} = require('../../service/app')

/**
 * 托盘插件
 */
class TrayService {
    constructor() {
        this.tray = null
    }

    /**
     * 创建托盘
     */
    create() {
        logger.info('[tray] load')
        const cfg = getConfig().tray
        const mainWindow = getMainWindow()
        // 托盘图标
        let iconPath = path.join(getBaseDir(), cfg.icon)
        // 托盘菜单功能列表
        let trayMenuTemplate = [
            {
                label: '主窗口',
                click: function () {
                    mainWindow.show()
                }
            },
            {
                label: '退出',
                click: function () {
                    electronApp.quit()
                }
            }
        ]
        // 点击关闭，最小化到托盘
        setCloseAndQuit(false)
        mainWindow.on('close', (event) => {
            if (getCloseAndQuit()) {
                return
            }
            if (appService.appCloseWindow === 'quit') {
                //退出
                electronApp.quit()
            } else {
                //最小化到托盘
                mainWindow.hide()
                event.preventDefault()
            }
        })
        // 实例化托盘
        this.tray = new Tray(iconPath)
        this.tray.setToolTip(cfg.title)
        const contextMenu = Menu.buildFromTemplate(trayMenuTemplate)
        this.tray.setContextMenu(contextMenu)
        // 点击托盘图标显示主窗口
        this.tray.on('click', (event, bounds, position) => {
            mainWindow.show()
        })
    }
}

TrayService.toString = () => '[class TrayService]'
module.exports = {
    trayService: new TrayService()
}